package com.itheima.app.manager;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Notification;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.User;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.db.BlackListService;
import com.itheima.service.db.NotificationService;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class SettingManager {

    @Reference
    private QuestionService questionService;

    @Reference
    private NotificationService notificationService;

    @Reference
    private BlackListService blackListService;

    public void saveOrUpdateQuestion(String content) {
        //获取当前登录用户的id
        Long userId = UserHolder.getId();
        //根据userId查询当前用户的陌生人问题
        Question question = questionService.findByUserId(userId);
        //如果为空
        if (question == null) {
            //将新问题保存
            question = new Question();
            question.setUserId(userId);
            question.setStrangerQuestion(content);
            questionService.save(question);
        } else {
            //不为空则执行修改操作
            question.setStrangerQuestion(content);
            questionService.updateById(question);
        }
    }

    public void saveOrUpdateNotification(Notification notification) {
        //获取当前用户id
        Long userId = UserHolder.getId();
        Notification dbNotification = notificationService.findByUserId(userId);
        if (dbNotification == null) {
            notification.setUserId(userId);
            notificationService.save(notification);
        } else {
            dbNotification.setGonggaoNotification(notification.getGonggaoNotification());
            dbNotification.setLikeNotification(notification.getLikeNotification());
            dbNotification.setPinglunNotification(notification.getPinglunNotification());
            notificationService.updateById(dbNotification);
        }
    }


    public PageBeanVo findBlackList(Integer page, Integer pageSize) {
        Long userId = UserHolder.getId();
        return blackListService.findBlackListByUid(userId, page, pageSize);
    }

    public void deleteBlackList(Long blackUserId) {
        Long userId = UserHolder.getId();
        blackListService.deleteByUid(userId, blackUserId);
    }

    @Reference
    private UserService userService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 修改手机号 -1 发送短信验证码
     */
    public void updateTelephoneSendCode() {
        //1.随机生成6位验证码
        String code = RandomUtil.randomNumbers(6);
        //设置个简单的验证码
        code = "123456";
        //2.查询当前用户id，获取它的手机号(给后面发送短信做准备)
        User user = UserHolder.get();
        String phone = userService.findPhoneByUserId(user.getId());

        //3.将验证码放入缓存去中存放五分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone,code, Duration.ofMinutes(5));
    }

    /**
     * 修改手机号 - 2 校验验证码
     * @param verificationCode
     * @return
     */
    public ResponseEntity checkVerificationCode(String verificationCode) {
        //1.定义返回值
        boolean verification = false;
        Map<String,Boolean> map = new HashMap<>();
        //2.获取用户id
        Long userId = UserHolder.getId();
        //3.获取手机号
        String phone = userService.findPhoneByUserId(userId);
        //4.从缓存区中获取验证码，看是否存不存在超时
        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);

        if (StrUtil.isEmpty(code)){
            //4.1 验证码为空，说明已失效
            return ResponseEntity.status(500).body(verification);
        }

        //5.没有生效则比较验证码是否正确
        if(!code.equals(verificationCode)){
            return ResponseEntity.status(500).body(verification);
        }

        //6.验证码正确
        verification = true;
        map.put("verification",verification);
        return ResponseEntity.ok(map);
    }

    /**
     * 修改手机号 - 3 保存
     * @param phone
     */
    public void updatePhone(String phone) {
        //1.获取当前用户对象
        User user = UserHolder.get();
        //2.修改手机号
        user.setPhone(phone);
        //3.执行
        userService.update(user);
    }
}
